package com.ruixun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruixun.common.PageData;
import com.ruixun.entity.User;
import com.ruixun.mapper.UserMapper;
import com.ruixun.query.UserPageQuery;
import com.ruixun.rvo.UserRvo;
import com.ruixun.service.UserService;
import com.ruixun.utils.PageUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 * @author ruixun
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;

    @Override
    public PageData<UserRvo> getPage(UserPageQuery userPageQuery) {
        // 构建分页对象
        IPage<User> page = new Page<>(userPageQuery.getPageNum(), userPageQuery.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getDeleted, 0); // 未删除的数据

        // 用户名模糊查询
        if (StringUtils.hasText(userPageQuery.getUserName())) {
            wrapper.like(User::getUserName, userPageQuery.getUserName());
        }

        // 排序（按创建时间倒序）
        wrapper.orderByDesc(User::getCreateTime);

        // 执行分页查询
        IPage<User> userPage = userMapper.selectPage(page, wrapper);

        // 转换结果
        List<UserRvo> rvoList = userPage.getRecords().stream()
                .map(this::convertToRvo)
                .collect(Collectors.toList());

        return new PageUtils<UserRvo>().convert(userPage.getCurrent(), userPage.getSize(), userPage.getTotal(),rvoList);
    }

    @Override
    public boolean addUser(User user) {
        return save(user);
    }

    @Override
    public boolean updateUser(User user) {
        return updateById(user);
    }

    @Override
    public boolean deleteUser(Long id) {
        User user = getById(id);
        if (user != null) {
            user.setDeleted(1); // 逻辑删除
            return updateById(user);
        }
        return false;
    }

    @Override
    public UserRvo getUserById(Long id) {
        User user = getById(id);
        return user != null ? convertToRvo(user) : null;
    }

    /**
     * 实体类转换为返回视图对象
     * @param user 用户实体
     * @return 返回视图对象
     */
    private UserRvo convertToRvo(User user) {
        UserRvo rvo = new UserRvo();
        BeanUtils.copyProperties(user, rvo);
        return rvo;
    }

}